from aiohttp import web
import socketio
import json

sio = socketio.AsyncServer(async_mode='aiohttp')
app = web.Application()
sio.attach(app)
onlineSids = []
loginClients = {}
@sio.event
async def connect(sid, environ,auth):
    print('connect ', sid)
    await sio.enter_room(sid,"chat")
    await sio.emit("id",sid,sid)
    await sio.emit("ip",environ['REMOTE_ADDR'],sid)
    print("connect REMOTE_ADDR = " + environ['REMOTE_ADDR'])
    # print(environ.keys())
    onlineSids.append(sid)
    # print(environ['aiohttp.request'].remote)
    # print(environ['aiohttp.request'].host)
    print(environ.get('X-Forwarded-For'))
    # for key in environ.keys():
    #     print(key)

@sio.event
async def disconnect(sid):
    print('disconnect ', sid)
    await sio.leave_room(sid,"chat")
    onlineSids.remove(sid)
    if sid in loginClients :
        print("disconnect = " + str(loginClients[sid]))
        del loginClients[sid]

    users = []
    for key,item in loginClients.items():
        user = {}
        user['id'] = key
        user['data'] = item
        users.append(user)
    print("当前在线数量：" + str(len(onlineSids)))
    await sio.emit("login",users,"chat",skip_sid=sid)

@sio.on("login")
async def login(sid,data):
    print("login " + sid)
    print(data)
    dict = json.loads(data)
    print(sio.get_environ(sid)['aiohttp.request'].remote)
    dict["ip"] = sio.get_environ(sid)['aiohttp.request'].remote
    loginClients[sid] = dict
    users = []
    for key,item in loginClients.items():
        print("当前登录:" + str(item))
        user = {}
        user['id'] = key
        user['data'] = item
        users.append(user)
    await sio.emit("login",users,"chat")

@sio.event
async def get_logins(sid):
    users = []
    for key,item in loginClients.items():
        user = {}
        user['id'] = key
        user['data'] = item
        users.append(user)
    await sio.emit("login",users,"chat")

@sio.on("signal")
async def signal(sid,data):
    print("signal > ")
    print(data)
    to = data["to"]
    await sio.emit("signal",data,to)

@sio.on("message")
async def message(sid,data):
    print("message > ")
    print(data)
    # print(sio.get_environ(sid)['aiohttp.request'].remote)
    # print("message REMOTE_ADDR" + sio.get_environ(sid)['REMOTE_ADDR'])

    await sio.emit("turnMessage",data,sid)

@sio.on("turnMessage")
async def turnMessage(sid,to,data):
    print("turnMessage > data len = " + str(len(data)))
    # print(data)
    await sio.emit("turnMessage",(sid,data),to)

# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    web.run_app(app,port=3000)
